package boc.sx.gateway.socket.client.handler;

import boc.sx.gateway.socket.client.NettyClient;
import com.alibaba.fastjson.JSONObject;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.URI;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

import static com.sun.deploy.net.HttpRequest.CONTENT_TYPE;

/*
 * @author zmx
 * @date 2022/8/18 10:04
 */
public class SimpleClientHandler  extends ChannelHandlerAdapter {

    private String uri;

    private String code;

    private Object sendMsg;

    public static AtomicInteger count = new AtomicInteger(0);


    public SimpleClientHandler(String uri,String code,Object sendMsg) {
        this.uri = uri;
        this.code = code;
        this.sendMsg = sendMsg;
    }

    public SimpleClientHandler() {
    }


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        String s = (String)msg;
        NettyClient.notifyThread(code,s);

        System.out.println( count.addAndGet(1) +":" +NettyClient.receiveMessage.get(code) +" size :" + NettyClient.receiveMessage.size());

    }


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        String msg = "";
        if(sendMsg instanceof  String){
            msg = (String)sendMsg;
        }else if(sendMsg instanceof JSONObject){
            msg = JSONObject.toJSONString(sendMsg);
        }else if(sendMsg instanceof Map){
            msg = JSONObject.toJSONString(sendMsg);
        }
        ctx.writeAndFlush(msg);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        super.channelReadComplete(ctx);
        ctx.close();
    }
}
